//
//  FortuneViewController.m
//  SmileWeather
//
//  Created by lanou3g on 15/9/17.
//  Copyright (c) 2015年 陶天海. All rights reserved.
//
#import "FortuneViewController.h"
#import "FortuneReusableView.h"
#import "FortuneCollectionViewCell.h"
#import "FortuneModel.h"
#import "FortuneDetailViewController.h"
#import "TapImageView.h"

@interface FortuneViewController ()
@property (nonatomic, strong)NSMutableArray *fortuneArray;
@property (nonatomic, strong)UICollectionView *collectionView;

@property (nonatomic, strong)UIActivityIndicatorView *act;
@property (nonatomic, strong)UIAlertView *alert;

@property (nonatomic, strong)UILabel *label;
@end

@implementation FortuneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"星座宝宝";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(buttonClick)];
    
    BlurImageView *blurImage = [[BlurImageView alloc] initWithFrame:kBounds];
    [self.view addSubview:blurImage];
    [self setCollectionView];
    [self reloadFortune];
    
}
//请求数据
- (void)reloadFortune{
    [self setAlert];
    NSURL *url = [NSURL URLWithString:kFortuneUrl];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:10.0];
    [request setHTTPMethod:@"GET"];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    if (data == nil) {
        [self.act stopAnimating];
        [self.alert dismissWithClickedButtonIndex:0 animated:YES];

        [self setLabel];
    }else{
        NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        for (NSArray *arr1 in array) {
            for (NSDictionary *dic in arr1) {
                FortuneModel *model = [[FortuneModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.fortuneArray addObject:model];
                }
            }
        [self.collectionView reloadData];
        [self.act stopAnimating];
        [self.alert dismissWithClickedButtonIndex:0 animated:YES];
        }
    }];
}
- (NSMutableArray *)fortuneArray{
    if (!_fortuneArray) {
        _fortuneArray = [[NSMutableArray alloc] init];
    }
    return _fortuneArray;
}
//加载没网状态下的label
- (void)setLabel{
    self.label = [[UILabel alloc] initWithFrame:CGRectMake(60, kHeight/2 - 50, kWidth/2 + 60, 70)];
    self.label.backgroundColor = [UIColor clearColor];
    self.label.userInteractionEnabled = YES;
    self.label.textColor = [UIColor whiteColor];
    self.label.text = @"网络不好,请重试";
    self.label.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.label];
    TapImageView *imageView = [[TapImageView alloc] initWithFrame:CGRectMake(185, 20, 30, 30) target:self action:@selector(tapImage)];
    imageView.image = [UIImage imageNamed:@"dateUp"];
    [self.label addSubview:imageView];
}
- (void)tapImage{
    [self.label removeFromSuperview];
    [self reloadFortune];
}
- (void)setAlert{
    self.alert = [[UIAlertView alloc] initWithTitle:@"正在加载..." message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
    self.act = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:(UIActivityIndicatorViewStyleGray)];
    [_act setFrame:CGRectMake(120, 48, 37, 37)];
    [_alert addSubview:_act];
    [_act startAnimating];
    [_alert show];
}
- (void)buttonClick{
    [self dismissViewControllerAnimated:NO completion:nil];
}
-(void)setCollectionView{
    //创建布局对象
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.minimumLineSpacing = 20;
    layout.itemSize = CGSizeMake((kWidth - 80) / 3, (kWidth + 10)/ 3);
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 25, 0);
    
    //创建集合视图
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(25, 64, kWidth - 50, kHeight - 64)collectionViewLayout:layout];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.backgroundColor = [UIColor clearColor];
    //注册
    [self.collectionView registerClass:[FortuneCollectionViewCell class] forCellWithReuseIdentifier:@"fortuneCell"];
    [self.collectionView registerClass:[FortuneReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    
    [self.view addSubview:_collectionView];
}
//增广视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    FortuneReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
    reusableView.title = @"12个星座小宝宝";
    return reusableView;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    CGSize size={375,40};
    return size;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.fortuneArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    FortuneCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"fortuneCell" forIndexPath:indexPath];
    FortuneModel *model = self.fortuneArray[indexPath.row];
      [cell.startImage sd_setImageWithURL:[NSURL URLWithString:model.icon] placeholderImage:[UIImage imageNamed:@"tarot2_crystal_img_017.png"]];
        cell.titleLabel.text = model.sname;
        cell.birthsLabel.text = model.cname;
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    FortuneDetailViewController *forVC = [[FortuneDetailViewController alloc] init];
    FortuneModel *model = self.fortuneArray[indexPath.row];
    forVC.model = model;
    [self transitionWithType:@"cube" WithSubtype:kCATransitionFromRight];
    [self.navigationController pushViewController:forVC animated:NO];
}

#pragma CATransition动画实现
- (void) transitionWithType:(NSString *) type WithSubtype:(NSString *) subtype
{
    //创建CATransition对象
    CATransition *animation = [CATransition animation];
    //设置运动时间
    animation.duration = 0.7f;
    //设置运动type
    animation.type = type;
    if (subtype != nil) {
        //设置子类
        animation.subtype = subtype;
    }
    //设置运动速度
    animation.timingFunction = UIViewAnimationOptionCurveEaseInOut;
    [self.navigationController.view.layer addAnimation:animation forKey:@"animation"];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
